<template>
    <div style="min-width: 829px">
        <div v-if="$route.path == '/dayReport'">
            <div class="vs-search-box">
                <el-tabs v-search-box-enter v-model="active" @tab-click="handleClick">
                    <el-tab-pane label="日报表汇总" name="0">
                        <el-form ref="form" :inline="true" :model="paging" label-width="110px">
                            <el-form-item label="年月份：">
                                <el-date-picker v-model="paging.month" type="month" placeholder="选择年月" format="yyyy-MM" value-format="yyyy-MM"> </el-date-picker>
                            </el-form-item>
                            <el-form-item class="vs-right-btns">
                                <el-button @click="reset">重置</el-button>
                                <el-button @click="handleCurrentChange(1)" type="primary">查询</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="日报表明细" name="1">
                        <el-form ref="form" :inline="true" :model="paging" label-width="110px">
                            <el-form-item label="">
                                <el-date-picker v-model="paging.date" type="date" placeholder="选择日期" :clearable="false" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :clearabled="false"> </el-date-picker>
                            </el-form-item>
                            <el-form-item class="vs-right-btns">
                                <el-button @click="reset">重置</el-button>
                                <el-button @click="handleCurrentChange(1)" type="primary">查询</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <div class="vs-table-box">
                <div class="operation-box clear-float">
                    <el-button v-if="utils.getIsShopowner()" style="margin-left: auto" @click="exportFn" icon="el-icon-download" type="primary">导出</el-button>
                </div>
                <el-table v-loading="loading" :data="tableData" header-row-class-name="has-gutter-table" style="width: 100%" border key="0" v-if="active == 0" max-height="500" show-summary :summary-method="getSummaries">
                    <el-table-column prop="id" label="序号" align="center"></el-table-column>
                    <el-table-column prop="date" label="日期" align="center"></el-table-column>
                    <!-- <el-table-column prop="store.title" label="门店名称" align="center"></el-table-column> -->
                    <el-table-column prop="sale" label="销售" align="center"></el-table-column>
                    <el-table-column prop="expenditure" label="店内支出" align="center"></el-table-column>
                    <el-table-column prop="payable" label="应打款" align="center"></el-table-column>
                    <el-table-column prop="deduction" label="营业款抵回款" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.deduction" placeholder="" @blur="blur(scope.row)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="actual" label="实际打款" align="center"></el-table-column>
                    <el-table-column prop="difference" label="差额" align="center"></el-table-column>
                    <el-table-column prop="remark" label="备注" align="center"> </el-table-column>
                </el-table>
                <table v-else id="dataTable" border cellspacing="0">
                    <thead>
                        <tr>
                            <td colspan="13">当日订单及收款</td>
                        </tr>
                        <tr>
                            <td>序号</td>
                            <td>姓名</td>
                            <td>网料</td>
                            <td>分类</td>
                            <td>长度（cm）</td>
                            <td>数量</td>
                            <td>订单总金额（元）</td>

                            <td>预付定金（元）</td>
                            <td>订单尾款（元）</td>
                            <td>收尾款（元）</td>

                            <td>退款金额</td>
                            <td colspan="2">备注</td>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in info.customized" :key="index">
                            <!-- <td v-for="i in 10" :key="i+'i'"></td> -->
                            <td>{{ item.id }}</td>
                            <td>{{ item.realname }}</td>
                            <td>{{ item.goods_name }}</td>
                            <td>{{ item.cate }}</td>
                            <td>{{ item.length }}</td>
                            <td>{{ item.number }}</td>
                            <td>{{ item.orders_payable | toFixed2Filter }}</td>

                            <template>
                                <td v-if="(item.yue_pay_type == 2 || item.yue_pay_type == 1) && !item.advance_amount">/</td>
                                <td v-else>{{ item.advance_amount | toFixed2Filter }}</td>

                                <td v-if="(item.yue_pay_type == 3 || item.yue_pay_type == 1) && !item.advance_amount">/</td>
                                <td v-else>{{ item.balance_amount | toFixed2Filter }}</td>

                                <td v-if="(item.yue_pay_type == 3 || item.yue_pay_type == 1) && !item.advance_amount">/</td>
                                <td v-else>{{ item.balance_meet_amount | toFixed2Filter }}</td>
                            </template>

                            <td>{{ item.return_price | toFixed2Filter }}</td>
                            <td colspan="2">{{ item.remarks }}</td>
                        </tr>
                        <tr>
                            <td colspan="5">当日合计</td>
                            <td>{{ numberToday }}</td>
                            <td>{{ orders_payableToday | toFixed2Filter }}</td>
                            <td>{{ advance_amountToday | toFixed2Filter }}</td>
                            <td>{{ balance_amountToday | toFixed2Filter }}</td>
                            <td>{{ balance_meet_amountToday | toFixed2Filter }}</td>
                            <td>{{ return_priceToday | toFixed2Filter }}</td>
                            <td colspan="2"></td>
                        </tr>
                        <tr>
                            <td colspan="5">本月累计</td>
                            <td>{{ info.customized_total.number }}</td>
                            <td>{{ info.customized_total.orders_payable | toFixed2Filter }}</td>
                            <td>{{ info.customized_total.advance_amount | toFixed2Filter }}</td>
                            <td>{{ info.customized_total.balance_amount | toFixed2Filter }}</td>
                            <td>{{ info.customized_total.balance_meet_amount | toFixed2Filter }}</td>
                            <td>{{ info.customized_total.return_price | toFixed2Filter }}</td>
                            <td colspan="2"></td>
                        </tr>
                        <tr>
                            <td colspan="6">护理产品收入</td>
                            <td colspan="2">服务费及充值</td>
                            <td colspan="5">每日开支明细</td>
                        </tr>
                        <tr>
                            <td>序号</td>
                            <td>姓名</td>
                            <td colspan="3">产品名称</td>
                            <td>金额</td>
                            <td>姓名</td>
                            <td>金额</td>
                            <td>序号</td>
                            <td>项目明细</td>
                            <td>当日发生</td>
                            <td>备注</td>
                            <td>本月累计</td>
                        </tr>
                        <tr v-for="(item, index) in info.list" :key="index + 'a'">
                            <template>
                                <td>{{ item.nursing.id }}</td>
                                <td>{{ item.nursing.realname }}</td>
                                <td colspan="3">{{ item.nursing.goods_name }}</td>
                                <td>{{ item.nursing.money | toFixed2Filter }}</td>
                                <td>{{ item.price.realname || '散客' }}</td>
                                <td>{{ item.price.price | toFixed2Filter }}</td>
                                <td>{{ item.spend.id }}</td>
                                <td>{{ item.spend.title }}</td>
                                <td>{{ item.spend.money | toFixed2Filter }}</td>
                                <td>{{ item.spend.remark }}</td>
                                <td>{{ item.spend.money_total | toFixed2Filter }}</td>
                            </template>
                        </tr>
                        <tr>
                            <td colspan="5">当日合计</td>
                            <td>{{ info.day_nursing | toFixed2Filter }}</td>
                            <td>当日合计</td>
                            <td>{{ info.day_price | toFixed2Filter }}</td>
                            <td colspan="2">当日合计</td>
                            <td>{{ info.day_spend | toFixed2Filter }}</td>
                            <td></td>
                            <td>{{ info.day_spend | toFixed2Filter }}</td>
                        </tr>
                        <tr>
                            <td colspan="5">本月累计</td>
                            <td>{{ info.nursing_total | toFixed2Filter }}</td>
                            <td>本月累计</td>
                            <td>{{ info.price_total | toFixed2Filter }}</td>
                            <td colspan="2">本月累计</td>
                            <td>{{ info.spend_total | toFixed2Filter }}</td>
                            <td></td>
                            <td>{{ info.spend_total | toFixed2Filter }}</td>
                        </tr>
                        <tr>
                            <td rowspan="4">结算</td>
                            <!-- <td>当日退卡总额</td> -->
                            <td>当月退卡总额</td>
                            <td>当日收款总合计</td>
                            <td colspan="2">昨日收款总累计</td>
                            <td colspan="2">本月收款总累计</td>
                            <td>当日开支</td>
                            <td colspan="2">昨日开支累计</td>
                            <td colspan="3">本月开支累计</td>
                        </tr>
                        <tr>
                            <!-- <td>{{ info.day_return_vip | toFixed2Filter }}</td> -->
                            <td>{{ info.month_return_vip | toFixed2Filter }}</td>
                            <td>{{ info.day_all_paid | toFixed2Filter }}</td>

                            <td colspan="2">{{ info.customized_first | toFixed2Filter }}</td>
                            <td colspan="2">{{ info.month_all_paid | toFixed2Filter }}</td>
                            <td>{{ info.day_spend | toFixed2Filter }}</td>
                            <td colspan="2">{{ info.spend_first | toFixed2Filter }}</td>
                            <td colspan="3">{{ info.spend_total | toFixed2Filter }}</td>
                        </tr>
                        <tr>
                            <td colspan="4">当日结余</td>
                            <td colspan="4">昨日结余累计</td>
                            <td colspan="4">本月结余累计</td>
                        </tr>
                        <tr>
                            <td colspan="4">{{ info.balance.day | toFixed2Filter }}</td>
                            <td colspan="4">{{ info.balance.first | toFixed2Filter }}</td>
                            <td colspan="4">{{ info.balance.month | toFixed2Filter }}</td>
                        </tr>
                        <tr>
                            <td>汇款</td>
                            <td>当日实际汇款总部</td>
                            <td colspan="3">{{ info.rem.day | toFixed2Filter }}</td>
                            <td>本月实际累计汇款总部</td>
                            <td>{{ info.rem.total | toFixed2Filter }}</td>
                            <td>当日汇款与日报表实际收款差额</td>
                            <td>{{ info.rem.day_diff | toFixed2Filter }}</td>
                            <td>本月汇款与日报表实际累计收款差额</td>
                            <td colspan="3">{{ info.rem.month_diff | toFixed2Filter }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <router-view></router-view>
    </div>
</template>

<script>
    import FileSaver from 'file-saver';
    import XLSX from 'xlsx';
    import XLSXD from 'xlsx-style';
    export default {
        data() {
            return {
                shopList: [],
                loading: false,
                paging: {
                    page: 1,
                    total: 0,
                    limit: 10,
                    month: '',
                    date: '',
                },
                tableData: [],
                active: '1',
                info: {
                    customized_total: {},
                    rem: {},
                    balance: {},
                },
            };
        },
        computed: {
            numberToday() {
                let s = 0;
                for (let i in this.info.customized) {
                    s += this.info.customized[i].number;
                }
                return s;
            },
            orders_payableToday() {
                let s = 0;
                for (let i in this.info.customized) {
                    s += this.info.customized[i].orders_payable * 1;
                }
                return s;
            },
            advance_amountToday() {
                let s = 0;
                for (let i in this.info.customized) {
                    s += this.info.customized[i].advance_amount * 1;
                }
                return s;
            },
            balance_amountToday() {
                let s = 0;
                for (let i in this.info.customized) {
                    s += this.info.customized[i].balance_amount * 1;
                }
                return s;
            },
            balance_meet_amountToday() {
                let s = 0;
                for (let i in this.info.customized) {
                    s += this.info.customized[i].balance_meet_amount * 1;
                }
                return s;
            },
            //退款金额
            return_priceToday() {
                let s = 0;
                for (let i in this.info.customized) {
                    s += this.info.customized[i].return_price * 1;
                }
                return s;
            },
        },
        filters: {
            toFixed2Filter(val) {
                if (typeof val == 'number' || val) {
                    return Number(val).toFixed(2);
                }
                return '';
            },
        },
        created() {
            if (this.$route.path == '/dayReport') {
                // this.paging.month = this.$moment(new Date()).format("YYYY-MM");
                this.paging.date = this.$moment(new Date()).format('YYYY-MM-DD');
                this.handleCurrentChange(1);
                this.handleClick();
            }
        },
        methods: {
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index == 0) {
                        sums[index] = '合计';
                        return;
                    }
                    const values = data.map((item) => Number(item[column.property]));
                    if (column.property == 'sale' || column.property == 'expenditure' || column.property == 'payable' || column.property == 'deduction' || column.property == 'actual' || column.property == 'difference') {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] = sums[index].toFixed(2);
                    } else {
                        sums[index] = '';
                    }
                });
                return sums;
            },
            // 导出
            async exportFn() {
                if (this.active == '0') {
                    let parms = {
                        month: this.paging.month,
                    };
                    if (!this.paging.month) {
                        return this.$message.warning('请选择月份');
                    }
                    let url = this.utils.data.baseURL + 'store/finance/exportDayReport';
                    this.utils.urlToBlob(url, '日报表', parms);
                } else {
                    this.exportTable('dataTable');
                }
            },
            exportTable(tableid) {
                var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
                // 这里的exportTable 就是给table起的id
                var wb = XLSX.utils.table_to_book(document.querySelector('#dataTable'), xlsxParam);
                let wbs = wb.Sheets.Sheet1;
                for (const key in wbs) {
                    if (key.indexOf('!') === -1 && wbs[key].v) {
                        wbs[key].s = {
                            alignment: {
                                horizontal: 'center',
                                vertical: 'center',
                                wrap_text: true,
                            },
                        };
                    }
                }
                wb.Sheets.Sheet1 = wbs;
                console.log(wb);
                var wbout = XLSXD.write(wb, { bookType: 'xlsx', bookSST: true, type: 'buffer' });
                try {
                    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '日报表汇总.xlsx');
                } catch (e) {
                    if (typeof console !== 'undefined') {
                        console.log(e, wbout);
                    }
                }
            },
            async blur(row) {
                let { code, data } = await this.$Http.setDayReport({
                    id: row.id,
                    deduction: row.deduction,
                });
                if (code) {
                    this.$message.success('修改成功!');
                    this.handleCurrentChange(1);
                }
            },
            handleClick(tab, event) {
                this.paging = Object.assign(this.$options.data().paging, {
                    date: this.paging.date,
                });
                this.handleCurrentChange(1);
            },
            async repairGetList() {
                // if (this.active == 1) {
                //     this.paging.date = this.$moment(new Date()).format('YYYY-MM-DD');
                // }
                let obj = Object.assign({}, this.paging);
                this.loading = true;
                if (this.active == 0) {
                    let { code, data } = await this.$Http.getDayReport(obj);
                    if (code) {
                        this.tableData = data;
                        // this.paging.total = data.total;
                    }
                } else {
                    let { code, data } = await this.$Http.getDayReportInfo(obj);
                    if (code) {
                        this.info = data;
                        let arr = [];
                        let nursing = data.nursing || [];
                        let price = data.price || [];
                        let spend = data.spend || [];
                        let nObj = { id: '', realname: '', goods_name: '', money: '' };
                        let pObj = { id: '', realname: '', price: '' };
                        let sObj = { id: '', title: '', money: '', remark: '', money_total: '' };
                        let n = nursing.length > price.length ? nursing.length : price.length;
                        n = spend.length > n ? spend.length : n;
                        for (let i = 0; i < n; i++) {
                            if (+nursing[i]?.money || +price[i]?.price || +spend[i]?.money_total) {
                                arr.push({
                                    nursing: nursing[i] ? nursing[i] : nObj,
                                    price: price[i] ? price[i] : pObj,
                                    spend: spend[i]?.money_total ? spend[i] : sObj,
                                });
                            }
                        }
                        console.log(arr);
                        this.info.list = arr;
                    }
                }
                this.loading = false;
            },
            reset() {
                //重置
                this.paging = this.$options.data().paging;
                this.paging.date = this.$moment(new Date()).format('YYYY-MM-DD');
                this.handleCurrentChange(1);
            },
            handleSizeChange(val) {
                this.paging.limit = val;
                this.repairGetList();
            },
            handleCurrentChange(val) {
                this.paging.page = val;
                this.repairGetList();
            },
        },
    };
</script>

<style lang="scss" scoped>
    .image-thumbnail {
        width: 130px;
        height: 130px;
    }

    .divTable {
        width: 100%;

        div {
            border-bottom: 1px solid #ebeef5;
            border-left: 1px solid #ebeef5;
            border-right: 1px solid #ebeef5;
            height: 50px;
            line-height: 50px;
            padding-left: 30px;
        }
    }

    table {
        width: 100%;
        border-collapse: collapse;
        border-spacing: 0;
        table-layout: fixed;

        td {
            border: 1px solid #ebeef5;
            text-align: center;
            height: 32px;
            color: #333333;
            padding: 0 5px;
            font-size: 14px;
        }
    }
</style>
